package com.xysl.service.impl;

import com.ruoyi.common.core.constant.UserConstants;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.system.api.domain.SysRole;
import com.xysl.api.domain.XyslUser;
import com.xysl.mapper.XyslPermissionMapper;
import com.xysl.service.IXyslPermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 用户权限处理
 *
 * @author ruoyi
 */
@Service
public class XyslPermissionServiceImpl implements IXyslPermissionService
{
    @Resource
    private XyslPermissionMapper permissionMapper;


    /**
     * 获取角色数据权限
     *
     * @return 角色权限信息
     */
    @Override
    public Set<String> getRolePermission(XyslUser user)
    {
        Set<String> roles = new HashSet<String>();
        roles.addAll(selectRolePermissionByUserId(user.getId()));
        return roles;
    }

    public Set<String> selectRolePermissionByUserId(Long userId)
    {
        List<String> perms = permissionMapper.selectRolePermissionByUserId(userId);
        Set<String> permsSet = new HashSet<>();
        for (String perm : perms)
        {
            if (StringUtils.isNotNull(perm))
            {
                permsSet.addAll(Arrays.asList(perm.trim().split(",")));
            }
        }
        return permsSet;
    }

    /**
     * 获取菜单数据权限
     *
     * @return 菜单权限信息
     */
    @Override
    public Set<String> getMenuPermission(XyslUser user)
    {
        Set<String> perms = new HashSet<String>();
        perms.addAll(selectMenuPermsByUserId(user.getId()));
        return perms;
    }


    public Set<String> selectMenuPermsByUserId(Long userId)
    {
        List<String> perms = permissionMapper.selectMenuPermsByUserId(userId);
        Set<String> permsSet = new HashSet<>();
        for (String perm : perms)
        {
            if (StringUtils.isNotEmpty(perm))
            {
                permsSet.addAll(Arrays.asList(perm.trim().split(",")));
            }
        }
        return permsSet;
    }
}
